package app.fugema.shop.main.goods.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;

import com.base.common.model.bean.BaseDataWrapper;
import com.base.common.model.http.jackSon.JacksonUtils;
import com.base.common.netBeanPackage.BaseResponse;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.DensityUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.RxTimer;
import com.base.common.utils.UIUtils;
import com.base.common.utils.span.SpanUtils;
import com.base.common.view.base.BaseActivity;
import com.base.common.view.widget.banner.BannerImageLoader;
import com.base.common.viewmodel.BaseViewObserver;
import com.jeremyliao.liveeventbus.LiveEventBus;
import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.databinding.GoodsDetailActivityBinding;
import app.fugema.shop.main.evaluate.adapter.EvaluateGoodsItemAdapter;
import app.fugema.shop.main.evaluate.model.EvaluatePageResult;
import app.fugema.shop.main.evaluate.view.EvaluateGoodsActivity;
import app.fugema.shop.main.goods.model.GoodsDetailResult;
import app.fugema.shop.main.goods.vm.GoodsVM;
import app.fugema.shop.main.home.model.GoodsDetailBean;
import app.fugema.shop.main.order.model.GroupBookingBean;
import app.fugema.shop.main.order.view.ShoppingCartBottomFragment;
import app.fugema.shop.main.wallet.model.BuyBean;
import app.fugema.shop.main.wallet.view.WalletPayDialogFragment;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import androidx.lifecycle.Observer;

public class ProductDetailActivity extends BaseActivity<GoodsDetailActivityBinding, GoodsVM>
{

    /**
     * @param context
     * @param goodsId
     */
    public static void start(Context context, int goodsId) {
        Intent intent = new Intent(context, GoodsDetailActivity.class);
        intent.putExtra("goodsId", goodsId);
        context.startActivity(intent);
    }

    public static void start(Context context, GroupBookingBean.RecordsBean goodBean) {
        if (goodBean == null) return;
        Intent intent = new Intent(context, GoodsDetailActivity.class);
        intent.putExtra("goodBean", JacksonUtils.transBean2Json(goodBean));
        context.startActivity(intent);
    }


    private int goodsId;
    private int type = 0; // 0商品详情  1秒杀  2拼团

    private EvaluateGoodsItemAdapter adapter;
    private RxTimer rxTimer;
    private boolean isShowPayDialog = false;//是否显示支付弹窗
    private BuyBean buyBean;
    private BigDecimal money;//支付金额
    private String userKey = "";
    @Override
    protected void onResume() {
        super.onResume();
        if (isShowPayDialog) {
            isShowPayDialog = false;
            if (buyBean != null) {
                addFragment(WalletPayDialogFragment.newInstance(buyBean));
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goods_detail_activity);
    }

    @Override
    protected void initNotificationReceipt() {
        super.initNotificationReceipt();
        LiveEventBus.get(AppConstants.EventKey.ORDER_CONFIRM_SUCCESS, BuyBean.class).observe(this, new Observer<BuyBean>() {
            @Override
            public void onChanged(BuyBean buyBean)
            {
                buyBean = buyBean;
                isShowPayDialog = true;
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();
        binding.ivImageLeftClose.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                finish();
            }
        });

        binding.tvTitleCenter.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                titleChange(true);
            }
        });

        binding.tvTextRight.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                titleChange(false);
            }
        });

        titleChange(true);


        SpanUtils.with(binding.tvLogisticsDesc).append("物流：").append("现货，预计2-5天送达").setTypeface(Typeface.DEFAULT_BOLD).create();

        SpanUtils.with(binding.tvStoreGuarantee).append("说明：")
                .append("XXX承诺100%正品").setTypeface(Typeface.DEFAULT_BOLD)
                .append("  |  ").setFontSize(DensityUtil.getDimens(R.dimen.dp_14)).setForegroundColor(0xffEEEEEE)
                .append("假一赔三").setTypeface(Typeface.DEFAULT_BOLD)
                .append("  |  ").setFontSize(DensityUtil.getDimens(R.dimen.dp_14)).setForegroundColor(0xffEEEEEE)
                .append("7天无理由退货").setTypeface(Typeface.DEFAULT_BOLD)
                .create();

        binding.tvEvaluateMore.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                EvaluateGoodsActivity.start(getActivity(), goodsId);
            }
        });
        adapter = new EvaluateGoodsItemAdapter();
        binding.rvRecyclerEvaluate.setAdapter(adapter);
    }


    private void titleChange(boolean isGoods) {
        if (isGoods) {
            binding.tvTitleCenter.setTextColor(0xff333333);
            binding.tvTitleCenter.setTypeface(Typeface.DEFAULT_BOLD);

            binding.tvTextRight.setTextColor(0xff999999);
            binding.tvTextRight.setTypeface(Typeface.DEFAULT);
            binding.nsvScrollView.scrollTo(0, 0);
        } else {
            binding.tvTextRight.setTextColor(0xff333333);
            binding.tvTextRight.setTypeface(Typeface.DEFAULT_BOLD);

            binding.tvTitleCenter.setTextColor(0xff999999);
            binding.tvTitleCenter.setTypeface(Typeface.DEFAULT);

            int y = binding.llGoodsDetail.getTop();

            binding.nsvScrollView.scrollTo(0, y);
        }
    }


    @Override
    protected void initData(Intent intent) {
        super.initData(intent);
        binding.llIntegral.setVisibility(View.GONE);//积分
        binding.llCoupon.setVisibility(View.GONE);//优惠券


        String goodsStr = intent.getStringExtra("goodBean");
        if (UIUtils.isEmpty(goodsStr))
        {
            goodsId = intent.getIntExtra("goodsId", 0);
            type = 0;
            binding.clTitleOne.setVisibility(View.GONE);
            binding.clTitleTwo.setVisibility(View.GONE);
            binding.clPrice.setVisibility(View.VISIBLE);
            binding.llGroupBooking.setVisibility(View.GONE);//拼团
            viewModel.getProductDetail(goodsId ,userKey)
                    .observe(this, new BaseViewObserver<LiveDataWrapper<GoodsDetailResult>>(this)
                    {
                        @Override
                        protected void onSuccess(LiveDataWrapper<GoodsDetailResult> data)
                        {
                            //data.data.getData()
                            GoodsDetailBean.DataBean dataBean = new GoodsDetailBean.DataBean();
                            setDataValues(dataBean);
                            money = dataBean.getPrice();
                            binding.flBottom.setVisibility(View.VISIBLE);
                            ShoppingCartBottomFragment fragment = (ShoppingCartBottomFragment) getSupportFragmentManager().findFragmentById(R.id.shoppingCart);
                            if (fragment != null)
                            {
                                //fragment.setDataBean(dataBean);
                            }

                        }

                        @Override
                        public boolean isEmptyData(LiveDataWrapper<GoodsDetailResult> data)
                        {
                            return UIUtils.isEmpty(data.data.getProduct());
                        }
                    });

        } else {
            binding.clTitleOne.setVisibility(View.VISIBLE);
            binding.clTitleTwo.setVisibility(View.VISIBLE);
            binding.clPrice.setVisibility(View.GONE);
            binding.flBottom.setVisibility(View.GONE);
            binding.rtvPay.setVisibility(View.VISIBLE);
            GroupBookingBean.RecordsBean goodBean = JacksonUtils.getJsonBean(goodsStr, GroupBookingBean.RecordsBean.class);
            if (goodBean != null)
            {
                GoodsDetailBean.DataBean dataBean = new GoodsDetailBean.DataBean();
                dataBean.setImgs(goodBean.getImgs());
                dataBean.setContent(goodBean.getContent());
                dataBean.setBrief(goodBean.getBrief());
                dataBean.setCategoryId(goodBean.getCategoryId());
                dataBean.setShopId(goodBean.getShopId());
                dataBean.setShopName(goodBean.getShopName());
                dataBean.setProdId(goodBean.getProdId());
                dataBean.setProdName(goodBean.getProdName());
                dataBean.setPrice(goodBean.getPrice());
                dataBean.setOriPrice(goodBean.getOriPrice());
                dataBean.setPic(goodBean.getPic());
                dataBean.setSaleCount(goodBean.getSaleCount());

                setDataValues(dataBean);
                binding.flBottom.setVisibility(View.GONE);


                type = goodBean.getSkId() == 0 ? 2 : 1;// 0商品详情  1秒杀  2拼团
                money = goodBean.getPrice();
                if (type == 1) {
                    binding.tvTimeText.setText("限时秒杀");
                    binding.rtvTitleFlag.setText("商品\n秒杀");
                    binding.llGroupBooking.setVisibility(View.GONE);//拼团
                } else {
                    binding.tvTimeText.setText("限时拼团");
                    binding.rtvTitleFlag.setText("商品\n拼团");
                    binding.llGroupBooking.setVisibility(View.GONE);//拼团
                    binding.rtvPay.setText("立即参团");
                }
                binding.rtvPay.setOnClickListener(new OnClickCheckedUtil() {
                    @Override
                    public void onClicked(View view) {
                        if (type == 1) {
                            skills(goodBean);
                        } else {
                            bookingGroup(goodBean);
                        }
                    }
                });
                if (rxTimer == null) {
                    rxTimer = new RxTimer();
                } else {
                    rxTimer.cancel();
                }

                rxTimer.interval(1000, new RxTimer.RxAction() {
                    @Override
                    public void action(long number) {
                        binding.rtvTimeHour.setText(goodBean.getTimeHour());
                        binding.rtvTimeMinute.setText(goodBean.getTimeMinute());
                        binding.rtvTimeSecond.setText(goodBean.getTimeSecond());
                    }
                });
            }
        }


        viewModel.getGoodsEvaluate( goodsId).observe(this, new BaseViewObserver<LiveDataWrapper<EvaluatePageResult>>(this) {
            @Override
            protected void onSuccess(LiveDataWrapper<EvaluatePageResult> data) {
                binding.llEvaluate.setVisibility(View.VISIBLE);
                adapter.setDataList(data.data.getData());
            }

            @Override
            public boolean isEmptyData(LiveDataWrapper<EvaluatePageResult> data) {
                return  UIUtils.isEmpty(data.data.getData());
            }

        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (rxTimer != null) {
            rxTimer.cancel();
        }
    }


    //秒杀
    private void skills(GroupBookingBean.RecordsBean goodBean) {

    }

    //拼团
    private void bookingGroup(GroupBookingBean.RecordsBean goodBean) {
        UIUtils.showToastSafes("开始拼团");
    }

    private void setDataValues(GoodsDetailBean.DataBean dataBean) {
        binding.setItem(dataBean);
        if (UIUtils.isNotEmpty(dataBean.getImgs())) {
            List<String> imageList = Arrays.asList(dataBean.getImgs().split(","));
            binding.banner.setImages(imageList).setImageLoader(new BannerImageLoader()).setDelayTime(3000).start();
        } else {
            binding.cllImages.setVisibility(View.GONE);
        }

        //binding.reRichEditor.loadRichEditorCode(binding.reRichEditor.getNewContent(dataBean.getContent()));

    }

}
